package com.taxi.driver.data.user.remote;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageManager;
import android.telephony.TelephonyManager;

import com.qianxx.utils.security.EncryptionUtil;
import com.taxi.driver.api.DriverApi;
import com.taxi.driver.common.AppConfig;
import com.taxi.driver.data.entity.AssessmentEntity;
import com.taxi.driver.data.entity.BillEntity;
import com.taxi.driver.data.entity.CancelReasonEntity;
import com.taxi.driver.data.entity.CommentEntity;
import com.taxi.driver.data.entity.ComplainEntity;
import com.taxi.driver.data.entity.DriverEntity;
import com.taxi.driver.data.entity.EvaluateEntity;
import com.taxi.driver.data.entity.FeedBackEntity;
import com.taxi.driver.data.entity.HomeEntity;
import com.taxi.driver.data.entity.MessageEntity;
import com.taxi.driver.data.entity.ProblemEntity;
import com.taxi.driver.data.entity.UpdateMsg;
import com.taxi.driver.data.entity.WithdrawalDetailsEntity;
import com.taxi.driver.data.entity.WithdrawaleRecordEntity;
import com.taxi.driver.data.user.UserSource;
import com.taxi.driver.module.vo.AddressVO;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;

import javax.inject.Inject;

import rx.Observable;

public class UserRemoteSource implements UserSource {

    private final DriverApi mDriverApi;
    private final Context mContext;

    private Observable<DriverEntity> mShareGetUserInfoObservable;
    private long mLastGetUserInfoStamp;

    @Inject
    UserRemoteSource(DriverApi driverApi, Context context) {
        mDriverApi = driverApi;
        mContext = context;
    }

    @Override
    public Observable<String> reqVerifyCode(String phone) {
        String noncestr = "" + System.currentTimeMillis();
        return mDriverApi.reqVerifyCode(phone, noncestr, getClientSign(phone, noncestr));
    }

    @Override
    public Observable<DriverEntity> reqLogin(String phone, String password) {
        HashMap<String, String> params = new HashMap<>();
        params.put("type", "" + AppConfig.getCarType());
        params.put("mobile", phone);
        params.put("password", password);
        params.put("deviceType", "1");
        params.put("deviceToken", getDeviceId());
        params.put("deviceVersion", getOsVersion());
        params.put("appVersion", getVerName());

        return mDriverApi.login(params);
    }

    @Override
    public Observable<String> reqLogout(double onWorkLng, double onWorkLat, String uploadText) {
        return mDriverApi.reqLogout(onWorkLng, onWorkLat, uploadText);
    }

    @Override
    public Observable<DriverEntity> getUserInfo() {
        if (mShareGetUserInfoObservable == null || mLastGetUserInfoStamp + 3000 < System.currentTimeMillis()) {
            mLastGetUserInfoStamp = System.currentTimeMillis();
            mShareGetUserInfoObservable = mDriverApi.getUserInfo().share();
        }
        return mShareGetUserInfoObservable;
    }

    @Override
    public void refreshUserInfo() {
        mShareGetUserInfoObservable = null;
    }

    @Override
    public void setUserInfo(DriverEntity entity) {

    }

    @Override
    public boolean isLogin() {
        return false;
    }

    @Override
    public int getCarLevelType() {
        return 0;
    }

    @Override
    public Observable<List<WithdrawaleRecordEntity>> widthdrawalRecord(int nowPage) {
        return mDriverApi.widthdrawalRecord(nowPage);
    }

    @Override
    public Observable<BillEntity> reqBills(int nowPage, int dateType, String start, String end, String type) {
        return mDriverApi.reqBills(nowPage, dateType, start, end, type);
    }

    @Override
    public Observable<List<ProblemEntity>> getProblems() {
        return mDriverApi.getProblems();
    }

    @Override
    public Observable<List<FeedBackEntity>> getFeedbacks(int nowPage) {
        return mDriverApi.getFeedbacks(nowPage);
    }

    @Override
    public Observable<String> addFeedback(String title, String content) {
        return mDriverApi.addFeedback(title, content);
    }

    @Override
    public Observable<WithdrawalDetailsEntity> getWithdrawalInfo(String cashUuid) {
        return mDriverApi.getWithdrawalInfo(cashUuid);
    }

    @Override
    public Observable<String> withdrawal(String cash, String collectAccount, int collectType, String password) {
        return mDriverApi.withdrawal(cash, collectAccount, collectType, password);
    }

    @Override
    public Observable<AssessmentEntity> reqAssessment(String startTime, String endTime) {
        return mDriverApi.reqAssessment(startTime, endTime);
    }

    @Override
    public Observable<EvaluateEntity> getEvaluates() {
        return mDriverApi.getEvaluates();
    }

    @Override
    public Observable<List<CommentEntity>> getYesterdayEvaluates(int nowPage) {
        return mDriverApi.getYesterdayEvaluates(nowPage);
    }

    @Override
    public Observable<String> resetPw(String newPsw, String oldPsw) {
        return mDriverApi.resetPw(newPsw, oldPsw);
    }

    @Override
    public Observable<String> validate(String phone, String idcard, int driverType) {
        return mDriverApi.validate(phone, idcard);
    }

    @Override
    public Observable<String> sendCode(String mobile) {
        return mDriverApi.sendCode(mobile);
    }

    @Override
    public Observable<String> verifyCode(String mobile, String identifyCode) {
        return mDriverApi.verifyCode(mobile, identifyCode);
    }

    @Override
    public Observable<String> resetPwd(String mobile, String identifyCode, String idcard, String password, int driverType) {
        return mDriverApi.resetPwd(mobile, identifyCode, idcard, password, driverType);
    }

    @Override
    public void setTempDriverEntity(DriverEntity entity) {

    }

    @Override
    public DriverEntity getTempDriverEntity() {
        return null;
    }

    @Override
    public Observable<HomeEntity> reqWorkInfo() {
        return mDriverApi.reqWorkInfo();
    }

    @Override
    public Observable<List<CancelReasonEntity>> reqCancelMsg() {
        return mDriverApi.reqCancelMsg();
    }

    @Override
    public Observable<List<ComplainEntity>> reqComplainMsg() {
        return mDriverApi.reqComplainMsg();
    }

    @Override
    public String getLocalDriverUuid() {
        return null;
    }

    @Override
    public List<AddressVO> getHistoryAddr() {
        return null;
    }

    @Override
    public void saveProvince(String province) {

    }

    @Override
    public void saveCity(String city) {

    }

    @Override
    public String getProvince() {
        return null;
    }

    @Override
    public String getCity() {
        return null;
    }

    @Override
    public void setNetworkStatus(boolean isDisconnect) {

    }

    @Override
    public Observable<List<MessageEntity>> getMsgList(int nowPage, int pageType) {
        return mDriverApi.getMsgList(nowPage, pageType);
    }

    @Override
    public Observable<UpdateMsg> updateMsg(String uuid, int status) {
        return mDriverApi.updateMsg(uuid, status);
    }

    @Override
    public Observable<String> deleteAll() {
        return mDriverApi.deleteMsg();
    }

    @Override
    public Observable<String> deleteMsg(String uuid) {
        return mDriverApi.deleteMsg(uuid);
    }

    @Override
    public Observable<String> uploadErrorMsg(String errorType, String errorMsg) {
        String errorTime = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(System.currentTimeMillis());
        return mDriverApi.uploadErrorMsg(errorTime, "PUSH", errorType, errorMsg, getDeviceId(), getOsVersion());
    }

    private static String getClientSign(String mobile, String noncestr) {
        String params = "mobile=" + mobile;
        params += "&noncestr=" + noncestr;
        params += "&key=Xmhldd957&o04-1mfvclk;ahgudflkd2523";
        return EncryptionUtil.md5Encode(params).toUpperCase();
    }

    /**
     * 获得设备型号
     *
     * @return
     */
    @SuppressLint("MissingPermission")
    private String getDeviceId() {
        try {
            TelephonyManager tm = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
            return tm.getDeviceId();
        } catch (Exception e) {
            return "";
        }
    }

    /**
     * 获取系统版本号
     */
    private static String getOsVersion() {
        String version = android.os.Build.MODEL + " -- " + android.os.Build.VERSION.RELEASE;
        return version;
    }

    /**
     * 获得app版本号
     */
    private String getVerName() {
        String verName = "1.0";
        try {
            String packageName = mContext.getPackageName();
            verName = mContext.getPackageManager().getPackageInfo(packageName, 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return verName;
    }
}